package evolution.visualization;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;

import evolution.individual.Individual;
import evolution.problem.FitnessFunction;

public class DataFileBuilder {

	public static String createGnuplotDataFile(Individual[][] populations)
			throws IOException {
		String pathToDatFile = null;
		File file = File.createTempFile("gnuplotData", ".tmp");
		file.deleteOnExit();
		Path target = file.toPath();
		try (BufferedWriter writer = Files.newBufferedWriter(target,
				Charset.defaultCharset())) {
			int iterations = populations.length;
			FitnessFunction fitnessFunction = populations[0][0]
					.getFitnessFunction();

			for (int i = 0; i < iterations; i++) {
				double[] chromosome = populations[i][0].getChromosome();
				writer.append(chromosome[0] + " ");
				writer.append(chromosome[1] + " ");
				writer.append(fitnessFunction
						.convertToRealValue(populations[i][0].getFitness())
						+ "");
				writer.newLine();
			}
			writer.flush();
			pathToDatFile = file.getAbsolutePath();
		} catch (IOException exception) {
			System.out.println("Error writing to file");
		}
		return pathToDatFile;
	}
}